﻿using Sunboxsoft.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sunboxsoft.ASMS.Server.Domain.Service
{
    public class DisableService
    {
        public ServiceResult DisablePackage(Guid id)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.EPackage entity = dbContext.Set<Entity.EPackage>().Where(p => p.Id == id && p.Status == Constant.CommonStatus.Enabled).SingleOrDefault();
                if (entity == null)
                {
                    return new ServiceResult();
                }

                entity.Status = Constant.CommonStatus.Disabled;
                dbContext.Entry<Entity.EPackage>(entity).State = System.Data.Entity.EntityState.Modified;
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("DisablePackage error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        public ServiceResult DisablePackageArray(Guid[] idArray)
        {
            if (idArray == null || idArray.Length == 0)
            {
                return new ServiceResult(1, "no id");
            }
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.AppendFormat("update ASMS_Package set [Status] = {0} where Id in (", Constant.CommonStatus.Disabled);
            for (int index = 0; index < idArray.Length; index++)
            {
                if (index == 0)
                {
                    sqlBuilder.AppendFormat("'{0}'", idArray[index]);
                }
                else
                {
                    sqlBuilder.AppendFormat(",'{0}'", idArray[index]);
                }
            }
            sqlBuilder.Append(")");
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                try
                {
                    dbContext.Database.ExecuteSqlCommand(sqlBuilder.ToString());
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("DisablePackageArray error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }
    }
}
